package network;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    //客户端在启动时需要指导服务器在哪！！
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        //对于客户端来说，不需要显示关联的端口
        //不代表没有端口，而是系统自动分配了个空闲的端口
        socket = new DatagramSocket();
        this.serverIp = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        //通过这个客户端可以多次进行交互。
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //1.先从控制台读取一个字符串过来
            System.out.println("-> ");
            String request = scanner.next();
            //2.把字符串构造成UDP packet，并进行发送
           DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
           socket.send(requestPacket);
            //3.客户端尝试读取服务器相应的数据
            DatagramPacket responsePacket = new DatagramPacket
                    (new byte[4096],4096);
            socket.receive(responsePacket);
            //4.把响应数据转换成String 显示出来
            String response = new String(responsePacket.getData(),0,
                    responsePacket.getLength());
            //
            System.out.printf("req: %s, resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",909);
        udpEchoClient.start();
    }
}
